import tkinter as tk
from tkinter import scrolledtext, messagebox, ttk
import socket
import threading

class ServerGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Socket服务器控制台")
        self.root.geometry("600x500")
        
        # 服务器状态
        self.server_running = False
        self.server_socket = None
        self.client_socket = None
        self.client_address = None
        
        # 创建界面
        self.create_widgets()
        
    def create_widgets(self):
        # 服务器控制区域
        control_frame = ttk.Frame(self.root)
        control_frame.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Label(control_frame, text="端口号:").pack(side=tk.LEFT)
        self.port_entry = ttk.Entry(control_frame, width=10)
        self.port_entry.insert(0, "12345")
        self.port_entry.pack(side=tk.LEFT, padx=(5, 10))
        
        self.start_button = ttk.Button(control_frame, text="启动服务器", command=self.start_server)
        self.start_button.pack(side=tk.LEFT, padx=(0, 5))
        
        self.stop_button = ttk.Button(control_frame, text="停止服务器", command=self.stop_server, state=tk.DISABLED)
        self.stop_button.pack(side=tk.LEFT, padx=(0, 5))
        
        self.status_label = ttk.Label(control_frame, text="服务器状态: 未启动")
        self.status_label.pack(side=tk.RIGHT)
        
        # 客户端信息区域
        client_frame = ttk.LabelFrame(self.root, text="客户端连接")
        client_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.client_info = ttk.Label(client_frame, text="无客户端连接")
        self.client_info.pack(padx=5, pady=5)
        
        # 消息发送区域
        send_frame = ttk.LabelFrame(self.root, text="发送消息")
        send_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.message_entry = ttk.Entry(send_frame, width=50)
        self.message_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5)
        self.message_entry.bind("<Return>", self.send_message)
        
        self.send_button = ttk.Button(send_frame, text="发送", command=self.send_message, state=tk.DISABLED)
        self.send_button.pack(side=tk.RIGHT, padx=5, pady=5)
        
        # 消息显示区域
        log_frame = ttk.LabelFrame(self.root, text="消息日志")
        log_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        self.log_text = scrolledtext.ScrolledText(log_frame, height=20, state=tk.DISABLED)
        self.log_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
    def start_server(self):
        try:
            port = int(self.port_entry.get())
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.server_socket.bind(('', port))
            self.server_socket.listen(5)
            self.server_running = True
            
            # 更新界面状态
            self.start_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.NORMAL)
            self.status_label.config(text=f"服务器状态: 运行中 (端口: {port})")
            self.log_message(f"服务器已启动，监听端口 {port}")
            
            # 启动监听线程
            self.listen_thread = threading.Thread(target=self.listen_for_clients, daemon=True)
            self.listen_thread.start()
            
        except Exception as e:
            messagebox.showerror("错误", f"启动服务器失败: {str(e)}")
            
    def stop_server(self):
        self.server_running = False
        if self.client_socket:
            try:
                self.client_socket.close()
            except:
                pass
            self.client_socket = None
            
        if self.server_socket:
            try:
                self.server_socket.close()
            except:
                pass
            self.server_socket = None
            
        # 更新界面状态
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)
        self.send_button.config(state=tk.DISABLED)
        self.status_label.config(text="服务器状态: 已停止")
        self.client_info.config(text="无客户端连接")
        self.log_message("服务器已停止")
        
    def listen_for_clients(self):
        while self.server_running:
            try:
                self.server_socket.settimeout(1.0)  # 设置超时以便能及时响应停止命令
                client_socket, client_address = self.server_socket.accept()
                
                # 如果已经有客户端连接，关闭新连接
                if self.client_socket:
                    client_socket.close()
                    self.log_message(f"拒绝连接请求: {client_address} (已有客户端连接)")
                    continue
                    
                self.client_socket = client_socket
                self.client_address = client_address
                
                # 更新界面
                self.root.after(0, self.on_client_connect)
                
                # 接收客户端消息的线程
                receive_thread = threading.Thread(target=self.receive_messages, daemon=True)
                receive_thread.start()
                
            except socket.timeout:
                continue
            except Exception as e:
                if self.server_running:
                    self.log_message(f"接受连接时出错: {str(e)}")
                break
                
    def on_client_connect(self):
        self.client_info.config(text=f"客户端地址: {self.client_address}")
        self.send_button.config(state=tk.NORMAL)
        self.log_message(f"客户端已连接: {self.client_address}")
        
    def receive_messages(self):
        while self.client_socket:
            try:
                data = self.client_socket.recv(1024)
                if data:
                    message = data.decode('utf-8')
                    self.root.after(0, lambda: self.log_message(f"接收: {message}"))
                else:
                    # 客户端断开连接
                    self.root.after(0, self.on_client_disconnect)
                    break
            except:
                self.root.after(0, self.on_client_disconnect)
                break
                
    def on_client_disconnect(self):
        if self.client_socket:
            self.client_socket.close()
            self.client_socket = None
            
        self.client_info.config(text="无客户端连接")
        self.send_button.config(state=tk.DISABLED)
        self.log_message("客户端已断开连接")
        
    def send_message(self, event=None):
        if not self.client_socket:
            messagebox.showwarning("警告", "没有客户端连接")
            return
            
        message = self.message_entry.get()
        if not message:
            messagebox.showwarning("警告", "请输入要发送的消息")
            return
            
        try:
            self.client_socket.send(message.encode('utf-8'))
            self.log_message(f"发送: {message}")
            self.message_entry.delete(0, tk.END)
        except Exception as e:
            messagebox.showerror("错误", f"发送消息失败: {str(e)}")
            self.on_client_disconnect()
            
    def log_message(self, message):
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, f"{message}\n")
        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)

# 原始服务器代码保持不变，但添加到类中以便控制
class OriginalServer:
    def __init__(self):
        self.s = socket.socket()
        self.host = socket.gethostname()
        self.port = 12345
        self.s.bind((self.host, self.port))
        self.s.listen(5)
        
    def run(self):
        while True:
            c, addr = self.s.accept()
            print("连接地址：", addr)
            msg = input("输入：")
            c.send(msg.encode("utf-8"))
            c.close()

if __name__ == "__main__":
    root = tk.Tk()
    app = ServerGUI(root)
    root.mainloop()